package handlers

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"zy35/api/request"
	"zy35/api/response"
	"zy35/dao"
)

// 文章发布
func AddBook(c *gin.Context) {
	var data request.AddBookRequest
	err := c.ShouldBind(&data)
	if data.Title == "" {
		c.JSON(500, gin.H{
			"Code": 500,
			"Msg":  "标题不能为空",
			"Data": nil,
		})
		return
	}
	if err != nil {
		c.JSON(500, gin.H{
			"Code": 500,
			"Msg":  "失败",
			"Data": nil,
		})
		return
	}
	book, _ := dao.CreateBook(data.Title, data.Context)

	c.JSON(200, gin.H{
		"Code": 200,
		"Msg":  "Success",
		"Data": book,
	})
}

// 文章点赞
func BookLike(c *gin.Context) {
	var data request.BookLikeRequest
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(500, gin.H{
			"Code": 500,
			"Msg":  "失败",
			"Data": nil,
		})
		return
	}
	result := dao.BookLike(data.BookId)
	c.JSON(200, gin.H{
		"Code": 200,
		"Msg":  "Success",
		"Data": result,
	})
}

// 添加评论
func AddReview(c *gin.Context) {
	var data request.AddReviewRequest
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(500, gin.H{
			"Code": 500,
			"Msg":  "失败",
			"Data": nil,
		})
		return
	}
	result := dao.AddReview(data.BookId, data.Review)
	c.JSON(200, gin.H{
		"Code": 200,
		"Msg":  "Success",
		"Data": result,
	})
}

// 回复评论
func ResReview(c *gin.Context) {
	var data request.ResReviewRequest
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(500, gin.H{
			"Code": 500,
			"Msg":  "失败",
			"Data": nil,
		})
		return
	}
	result := dao.ResReview(data.BookId, data.Review, data.FatherId)
	c.JSON(200, gin.H{
		"Code": 200,
		"Msg":  "Success",
		"Data": result,
	})
}

// 评论点赞
func AddReviewLike(c *gin.Context) {
	var data request.AddReviewLikeRequest
	err := c.ShouldBind(&data)
	if err != nil {
		c.JSON(500, gin.H{
			"Code": 500,
			"Msg":  "失败",
			"Data": nil,
		})
		return
	}
	result := dao.AddReviewLike(data.ReviewId)
	if result == nil {
		c.JSON(500, gin.H{
			"code": 500,
			"msg":  "error",
			"data": nil,
		})
		return
	}
	c.JSON(200, gin.H{
		"Code": 200,
		"Msg":  "Success",
		"Data": result,
	})
}

func GetBookDetail(c *gin.Context) {
	value := c.Query("id")
	id, err := strconv.Atoi(value)
	book := dao.GetBookId(id)
	if err != nil {
		c.JSON(500, gin.H{
			"Code": 500,
			"Msg":  "失败",
			"Data": nil,
		})
		return
	}
	book1 := response.GetBookDetailRes{
		Id:        book.Id,
		Title:     book.Title,
		Context:   book.Context,
		Deleted:   book.Deleted,
		CreatedAt: book.CreatedAt,
		UpdatedAt: book.UpdatedAt,
		LikeNum:   dao.CreateLikeNum(book.Id),
	}
	c.JSON(200, gin.H{
		"Code": 200,
		"Msg":  "Success",
		"Data": book1,
	})
}
